package cn.iocoder.yudao.module.cmt.service.content;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.content.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.content.ContentPostCategoryDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.content.ContentPostCategoryMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class ContentPostCategoryServiceImpl implements ContentPostCategoryService {

    @Resource
    private ContentPostCategoryMapper contentPostCategoryMapper;

    @Override
    public Long createPostCategory(ContentPostCategorySaveReqVO createReqVO) {
        ContentPostCategoryDO postCategory = BeanUtils.toBean(createReqVO, ContentPostCategoryDO.class);
        contentPostCategoryMapper.insert(postCategory);
        return postCategory.getId();
    }

    @Override
    public void updatePostCategory(ContentPostCategorySaveReqVO updateReqVO) {
        validatePostCategoryExists(updateReqVO.getId());
        ContentPostCategoryDO updateObj = BeanUtils.toBean(updateReqVO, ContentPostCategoryDO.class);
        contentPostCategoryMapper.updateById(updateObj);
    }

    @Override
    public void deletePostCategory(Long id) {
        validatePostCategoryExists(id);
        contentPostCategoryMapper.deleteById(id);
    }

    private void validatePostCategoryExists(Long id) {
        if (contentPostCategoryMapper.selectById(id) == null) {
            throw exception(POST_CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public ContentPostCategoryDO getPostCategory(Long id) {
        return contentPostCategoryMapper.selectById(id);
    }

    @Override
    public PageResult<ContentPostCategoryDO> getPostCategoryPage(ContentPostCategoryPageReqVO pageReqVO) {
        return contentPostCategoryMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePostCategoryListByIds(List<Long> ids) {
        ids.forEach(this::validatePostCategoryExists);
        contentPostCategoryMapper.deleteBatchIds(ids);
    }

}
